import { NextRequest, NextResponse } from 'next/server';
import UserModel, { WorkExperience } from '@/models/user';
import { authMiddleware, TokenPayload } from '@/utils/auth';

// 获取所有工作经历
export async function GET(request: NextRequest) {
  try {
    // 验证用户身份
    const authResult = await authMiddleware(request);
    if (authResult instanceof NextResponse) {
      return authResult; // 返回错误响应
    }

    const decoded = authResult as TokenPayload;
    const userId = decoded.id;

    // 获取用户的工作经历
    const workExperiences = await UserModel.getWorkExperiences(userId);

    return NextResponse.json(
      { workExperiences },
      { status: 200 }
    );

  } catch (error) {
    console.error('获取工作经历错误:', error);
    return NextResponse.json(
      { error: '服务器错误，请稍后再试' },
      { status: 500 }
    );
  }
}

// 添加工作经历
export async function POST(request: NextRequest) {
  try {
    // 验证用户身份
    const authResult = await authMiddleware(request);
    if (authResult instanceof NextResponse) {
      return authResult; // 返回错误响应
    }

    const decoded = authResult as TokenPayload;
    const userId = decoded.id;

    // 获取请求数据
    const body = await request.json();
    const workExpData = body as Partial<WorkExperience>;

    // 添加用户ID和必填字段
    const workExp = {
      company: '',
      position: '',
      start_date: '',
      ...workExpData,
      user_id: userId
    } as WorkExperience;

    // 验证必填字段
    if (!workExp.company || !workExp.position || !workExp.start_date) {
      return NextResponse.json(
        { error: '公司名称、职位和开始日期不能为空' },
        { status: 400 }
      );
    }

    // 添加工作经历
    const workExpId = await UserModel.addWorkExperience(workExp);

    // 获取添加后的工作经历列表
    const workExperiences = await UserModel.getWorkExperiences(userId);

    return NextResponse.json(
      {
        message: '添加工作经历成功',
        workExperienceId: workExpId,
        workExperiences
      },
      { status: 201 }
    );

  } catch (error) {
    console.error('添加工作经历错误:', error);
    return NextResponse.json(
      { error: '服务器错误，请稍后再试' },
      { status: 500 }
    );
  }
}